/*
 * @Description:
 * @Version: V1.0
 * @Author: zw_1520@163.com
 * @Date: 2024-09-02 08:42:26
 * @LastEditors: zw_1520@163.com
 * @LastEditTime: 2025-07-02 15:20:16
 * Copyright (C) All rights reserved.
 */

#include "robot_grpc_communicator.h"

// Requests each key in the vector and displays the key and its corresponding
// value as a pair.

void StreamDataReactor::SendData(const GeneralMsg &request) {
  if (!write_in_progress_) {
    request_ = request;
    write_in_progress_ = true;
    StartWrite(&request_);
  } else {
    GeneralMsg temp_request;
    temp_request = request;
    request_queue_.push(temp_request);
  }
}

void StreamDataReactor::OnWriteDone(bool ok) {
  write_in_progress_ = false;
  if (ok) {
    if (!request_queue_.empty()) {
      GeneralMsg next_request = request_queue_.front();
      request_queue_.pop();
      StartWrite(&next_request);
    }
  } else {
    // Finish(Status::CANCELLED);
  }
}

void StreamDataReactor::OnReadDone(bool ok) {
  if (ok) {
    std::cout << "Received from server: " << std::endl;
    RCLCPP_INFO(rclcpp::get_logger("StreamDataReactor"),
                "*****************Received from server***********.");
    StartRead(&response_);
  } else {
    // Finish(Status::OK);
  }
}

void StreamDataReactor::OnDone(const Status &status) {
  if (!status.ok()) {
    std::cerr << "Stream closed with error: " << status.error_message()
              << std::endl;
  } else {
    std::cout << "Stream closed successfully." << std::endl;
  }
  delete this;
}

void RobotGrpcClient::sendData(const GeneralMsg &request) {
  reactor_->SendData(request);
}
